package cn.edu.sjtu.process_management.controller;

import cn.edu.sjtu.process_management.model.OperatorSet;
import cn.edu.sjtu.process_management.model.Result;
import cn.edu.sjtu.process_management.service.OperatorSetService;
import cn.edu.sjtu.process_management.util.JWTUtil;
import cn.edu.sjtu.process_management.util.ResultUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class OperatorSetController {

    private final OperatorSetService operatorSetService;

    public OperatorSetController(OperatorSetService operatorSetService) {
        this.operatorSetService = operatorSetService;
    }

    @GetMapping(value = "/operator/ECNs")
    public Result findECNsOfOperator(@RequestHeader("Authorization") String token) {
        String userId = JWTUtil.decodeUserId(token);
        List<JSONObject> ret = operatorSetService.findsECNsOfOperator(userId);
        return ResultUtil.success(ret);
    }


    @GetMapping(value = "/operator/maintain/ECNs")
    public Result findECNsByMaintainer(@RequestParam("userId") String userId) {
        List<JSONObject> ret = operatorSetService.findsECNsOfOperator(userId);
        return ResultUtil.success(ret);
    }

    /**
     * return tasks of the corresponding ecn
     *
     * @param instanceId e.g. http://sp-01.root3:8080 aka http://${name}.${namespace}:${port}
     * @return tasks
     */
    @GetMapping(value = "/operator/tasks")
    public JSONObject findTasksOfECN(String instanceId) {
        return operatorSetService.findTasksOfECN(instanceId);
    }

    /**
     * start a task called by fronted and forward message to ecn
     *
     * @param operation start || end
     * @param taskInfo  instanceId other params
     * @return response of ecn
     */
    @PutMapping(value = "/ecn/{operation}")
    public JSONObject operateTask(@PathVariable String operation,
                                  @RequestBody JSONObject taskInfo) {
        String instanceId = taskInfo.getString("instanceId");
        return operatorSetService.operateTask(operation, instanceId, taskInfo);
    }

    @PostMapping(value = "/operator/relation")
    public Result createOperatorSet(@RequestHeader("Authorization") String token, @RequestBody OperatorSet operatorSet) {
        String maintainerId = JWTUtil.decodeUserId(token);

        operatorSetService.updateOperatorSet(maintainerId, operatorSet);
        return ResultUtil.success();
    }

    // instanceId 是一个类似url的东西，不能设为PathVariable
    @DeleteMapping(value = "/operator/relation")
    public Result deleteOperatorSet(String instanceId) {
        operatorSetService.deleteOperatorSet(instanceId);
        return ResultUtil.success();
    }
}
